package com.xyxy.platform.modules.service.trade.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xyxy.platform.modules.core.file.SystemFileService;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.entity.IsDelete;
import com.xyxy.platform.modules.entity.common.SysArea;
import com.xyxy.platform.modules.entity.content.Article;
import com.xyxy.platform.modules.entity.content.ArticleTypes;
import com.xyxy.platform.modules.entity.image.ImageItem;
import com.xyxy.platform.modules.entity.image.ImagePkg;
import com.xyxy.platform.modules.entity.image.ImageTypes;
import com.xyxy.platform.modules.entity.trade.*;
import com.xyxy.platform.modules.repository.mybatis.content.ArticleMapper;
import com.xyxy.platform.modules.repository.mybatis.image.ImagePkgMapper;
import com.xyxy.platform.modules.repository.mybatis.trade.*;
import com.xyxy.platform.modules.service.common.address.AddressService;
import com.xyxy.platform.modules.service.content.ArticleService;
import com.xyxy.platform.modules.service.image.ImageItemService;
import com.xyxy.platform.modules.service.image.ImagePkgService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.modules.service.member.vo.MemberDetail;
import com.xyxy.platform.modules.service.sns.CollectionService;
import com.xyxy.platform.modules.service.sns.GoodFollowService;
import com.xyxy.platform.modules.service.trade.*;
import com.xyxy.platform.modules.service.trade.utils.GoodsUtils;
import com.xyxy.platform.modules.service.trade.vo.GoodsDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional(readOnly = false)
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ImagePkgMapper imagePkgMapper;
    @Autowired
    private ImageItemService imageItemService;
    @Autowired
    private ServerTagsMapper serverTagsMapper;
    @Autowired
    private GoodsServerTagMapper goodsServerTagMapper;
    @Autowired
    private ServerTimeMapper serverTimeMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private GoodFollowMapper goodFollowMapper;
    @Autowired
    private AddressService addressService;
    @Autowired
    private GoodFollowService goodFollowService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private GoodsCommentService goodsCommentService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private SystemFileService systemFileService;
    @Autowired
    private GoodsServerTimeService serverTimeService;
    @Autowired
    private ImagePkgService imagePkgService;
    @Autowired
    private ServerTagService serverTagService;


    @Override
    @Transactional(readOnly = true)
    public Goods selectByPrimaryId(Long id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Goods selectGoodsByGoodsId(String goodsSn) {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.or().andGoodsSnEqualTo(goodsSn);
        List<Goods> goodsLits = goodsMapper.selectByExample(goodsExample);
        if (goodsLits != null && goodsLits.size() > 0) {
            return goodsLits.get(0);
        }
        return null;
    }

    @Override
    public boolean saveGoods(GoodsDto goodsDto) throws RuntimeException {
        // 保存文章内容
        Article article = new Article();
        article.setArticleTypeId(ArticleTypes.GOODS_DETAIL.getTypeId());
        article.setTitle(goodsDto.getGoodsName());

        // 从html内容中读取图片, 处理.
        String content = systemFileService.changeImageFileStatusFromHtml(goodsDto.getContent());
        article.setContent(content);

        article.setAuthor(goodsDto.getMemberName());
        article.setIsShow(1);
        article.setIsDel(IsDelete.NO.ordinal());
        Date now = new Date();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        if (null == articleService.insertArticle(article)) {
            throw new RuntimeException("商品文章保存错误");
        }
        // 处理封面图片
        String[] goodPics = goodsDto.getGoodPics();
        ImagePkg imagePkg = new ImagePkg();
        if (goodPics != null && goodPics.length > 0) {
            imagePkgMapper.insert(imagePkg);
            long pkgId = imagePkg.getId();
            for (int i = 0; i < goodPics.length; i++) {
                String imageUrl = goodPics[i];
                ImageItem imageItem = new ImageItem();
                imageItem.setImagePkgId(pkgId);
                imageItem.setImageTypeId(ImageTypes.GOODS_COVERS_IMAGES.getTypeId());
                imageItem.setIdx(i);
                // 文件处理
                imageItem.setUri(systemFileService.getFileNameFromUrl(imageUrl));
                imageItemService.insert(imageItem);
            }
        }
        // 添加商品
        Goods goods = new Goods();
        goods.setCatId(goodsDto.getCateId());
        goods.setGoodsSn(GoodsUtils.getGoodsSn());
        goods.setGoodsName(goodsDto.getGoodsName());
        goods.setGoodsCompanyNote(goodsDto.getGoodUnit());
        goods.setClickCount(0);
        goods.setMemberId(goodsDto.getMemberId());
        goods.setMarketPrice(new BigDecimal(goodsDto.getGoodPrice()));
        goods.setShopPrice(new BigDecimal(goodsDto.getGoodPrice()));
        goods.setServerType(goodsDto.getType());
        goods.setServerTimeNote(goodsDto.getTimeNote());
        goods.setGoodsArticleId(article.getArticleId());
        goods.setIsSale(1);
        goods.setCreateTime(now);
        goods.setUpdateTime(now);
        goods.setIsDel(IsDelete.NO.ordinal());
        goods.setIsBest(0);
        goods.setIsNew(0);
        goods.setIsHot(0);
        goods.setIsPromote(0);
        goods.setGoodsStatus(1);
        goods.setGoodsImgPkgid(imagePkg.getId());
        boolean isSaveGoods = false;
        try {
            isSaveGoods = goodsMapper.insert(goods) > 0;
        } catch (Exception e) {
            goods.setGoodsSn(GoodsUtils.getGoodsSn());
            isSaveGoods = goodsMapper.insert(goods) > 0;
        }
        if (!isSaveGoods) {
            throw new RuntimeException("商品文章保存错误");
        }

        // 处理服务时段
        if (StringUtils.isNotEmpty(goodsDto.getTime())) {
            List<GoodsServerTime> goodsServerTimeList = Lists.newArrayList();
            // 时间段, ps: 1-1,2-2,3-3,
            // 第一个数为位星期几, 1至6, 0为星期日;
            // 第二个数为: com.xyxy.platform.modules.entity.trade.GoodsServerTimeDefine 服务时间段范围定义 idx, 时间段标识
            String[] timeRanges = goodsDto.getTime().split(",");
            for (String timeRangeStr : timeRanges) {
                String[] timeRange = timeRangeStr.split("-");
                Integer week = Integer.parseInt(timeRange[0]);
                Integer serverTimeDefineIdx = Integer.parseInt(timeRange[1]);
                goodsServerTimeList.add(new GoodsServerTime(week, serverTimeDefineIdx));
            }
            serverTimeService.save(goodsServerTimeList, goods.getGoodsId());
        }

        String tag = goodsDto.getTags();
        if (!StringUtils.isEmpty(tag)) {
            // 处理商品标签云
            String[] goodsTagNames = StringUtils.split(tag, ",");
            ServerTagsExample serverTagsExample = null;
            List<ServerTags> serverTagsList = null;
            ServerTags serverTag = null;
            for (String tagName : goodsTagNames) {
                serverTagsExample = new ServerTagsExample();
                serverTagsExample.or().andTagNameEqualTo(tagName.trim());
                serverTagsList = serverTagsMapper.selectByExample(serverTagsExample);
                if (Collections3.isEmpty(serverTagsList)) {
                    serverTag = new ServerTags();
                    serverTag.setTagName(tagName);
                    serverTag.setCreateTime(new Date());
                    serverTagsMapper.insert(serverTag);
                } else {
                    serverTag = serverTagsList.get(0);
                }
                // 处理商品标签
                GoodsServerTag goodsServerTag = new GoodsServerTag();
                goodsServerTag.setCreateTime(now);
                goodsServerTag.setGoodsId(goods.getGoodsId());
                goodsServerTag.setServerTagId1(serverTag.getServerTagId());
                goodsServerTagMapper.insert(goodsServerTag);
            }
        }

        return true;
    }

    @Override
    public boolean updateGoods(GoodsDto goodsDto) throws RuntimeException {
        Goods entity = goodsMapper.selectByPrimaryKey(goodsDto.getGoodId());
        if (null == entity) return false;
        Date now = new Date();
        // 保存文章内容
        Article article = articleService.selectById(entity.getGoodsArticleId());
        // 从html内容中读取图片, 处理.
        String content = systemFileService.changeImageFileStatusFromHtml(goodsDto.getContent());
        if (null == article) { //new
            article = new Article();
            article.setArticleTypeId(ArticleTypes.GOODS_DETAIL.getTypeId());
            article.setTitle(goodsDto.getGoodsName());
            article.setContent(content);
            article.setAuthor(goodsDto.getMemberName());
            article.setIsShow(1);
            article.setIsDel(IsDelete.NO.ordinal());
            article.setCreateTime(now);
            article.setUpdateTime(now);
            articleService.insertArticle(article);
        } else {//update
            article.setContent(content);
            article.setUpdateTime(now);
            articleService.update(article);
        }

        // 处理封面图片
        List<String> imageUrlList = (null == goodsDto.getGoodPics() ? Lists.<String>newArrayList() : Lists.newArrayList(goodsDto.getGoodPics()));
        List<String> imageUriList = imageItemService.convertUrlToUri(imageUrlList);
        ImagePkg imagePkg = imagePkgService.findById(entity.getGoodsImgPkgid());
        if (null == imagePkg) { //new
            imagePkgService.insert(imagePkg);
            for (String imageUri : imageUriList) {
                ImageItem imageItem = new ImageItem();
                imageItem.setImagePkgId(imagePkg.getId());
                imageItem.setImageTypeId(ImageTypes.GOODS_COVERS_IMAGES.getTypeId());
                imageItem.setIdx(imageUrlList.indexOf(imageUri));
                imageItem.setUri(imageUri);
                imageItemService.insert(imageItem);
            }
        } else { //update
            //先删除原有数据
            List<ImageItem> currentImageItemList = imageItemService.findImageItemList(imagePkg.getId(), ImageTypes.GOODS_COVERS_IMAGES);
            for (ImageItem imageItem : currentImageItemList) {
                // 原有文件不包含在新提交数据中则删除
                imageItemService.delete(imageItem, imageUriList.contains(imageItem.getUri()));
            }
            //插入新数据
            for (String uri : imageUriList) {
                ImageItem imageItem = new ImageItem();
                imageItem.setImagePkgId(imagePkg.getId());
                imageItem.setImageTypeId(ImageTypes.GOODS_COVERS_IMAGES.getTypeId());
                imageItem.setIdx(imageUriList.indexOf(uri));
                imageItem.setUri(uri);
                imageItemService.insert(imageItem);
            }
        }

        // 添加商品
        entity.setCatId(goodsDto.getCateId());
        entity.setGoodsName(goodsDto.getGoodsName());
        entity.setGoodsCompanyNote(goodsDto.getGoodUnit());
        entity.setMarketPrice(new BigDecimal(goodsDto.getGoodPrice()));
        entity.setShopPrice(new BigDecimal(goodsDto.getGoodPrice()));
        entity.setServerType(goodsDto.getType());
        entity.setServerTimeNote(goodsDto.getTimeNote());
        entity.setGoodsArticleId(article.getArticleId());
        entity.setIsSale(0);//修改后为关闭状态
        entity.setUpdateTime(now);
        //entity.setIsBest(0);
        //entity.setIsNew(0);
        //entity.setIsHot(0);
        //entity.setIsPromote(0);
        //entity.setGoodsStatus(1);
        //entity.setGoodsImgPkgid(imagePkg.getId());
        goodsMapper.updateByPrimaryKey(entity);

        // 处理服务时段
        //删除原有
        List<String> serverTimeRangeList = null == goodsDto.getTime() ? Lists.<String>newArrayList() : Lists.newArrayList(goodsDto.getTime().split(","));
        List<GoodsServerTime> goodsServerTimeList = Lists.newArrayList();
        // 时间段, ps: 1-1,2-2,3-3,
        // 第一个数为位星期几, 1至6, 0为星期日;
        // 第二个数为: com.xyxy.platform.modules.entity.trade.GoodsServerTimeDefine 服务时间段范围定义 idx, 时间段标识
        for (String timeRangeStr : serverTimeRangeList) {
            String[] timeRange = timeRangeStr.split("-");
            if (null == timeRange || timeRange.length != 2) continue;
            Integer week = Integer.parseInt(timeRange[0]);
            Integer serverTimeDefineIdx = Integer.parseInt(timeRange[1]);
            goodsServerTimeList.add(new GoodsServerTime(week, serverTimeDefineIdx));
        }
        serverTimeService.save(goodsServerTimeList, entity.getGoodsId());

        //服务标签
        List<ServerTags> serverTagsList = Lists.newArrayList();
        List<String> tagNameList = null == goodsDto.getTags() ? Lists.<String>newArrayList() : Lists.newArrayList(goodsDto.getTags().split(","));
        for (String tagName : tagNameList) {
            if(StringUtils.isEmpty(tagName)) continue;
            ServerTags serverTag = serverTagService.findByName(tagName);
            if (null == serverTag) {
                serverTag = new ServerTags();
                serverTag.setTagName(tagName);
                serverTag.setCreateTime(new Date());
                serverTagService.insert(serverTag);
            }
            serverTagsList.add(serverTag);
        }
        serverTagService.save(serverTagsList, entity.getGoodsId());

        return true;
    }

    @Override
    public Category selectCategoryById(long id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        return category;
    }

    @Override
    public PageInfo<GoodsDto> selectHotGoodsByMap(Map<String, Object> params) {
        // 分页参数
        Integer pageNum = params.containsKey("pageNum") ? Integer.parseInt(params.get("pageNum").toString()) : 1;
        Integer pageSize = params.containsKey("pageSize") ? Integer.parseInt(params.get("pageSize").toString()) : 10;

        // 服务类别ID 转换
        if (params.containsKey("categoryId")) {
            Long categoryId = Long.parseLong(params.get("categoryId").toString());
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            String idPath = category.getMakeSelfAsParentIds();
            params.put("idPath", idPath);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goodsList = goodsMapper.selectHotByMap(params);

        // 包装DTO
        List<GoodsDto> goodsDtoList = Lists.newArrayList();
        if (Collections3.isNotEmpty(goodsList)) {
            for (Goods goods : goodsList) {
                GoodsDto goodDto = fullGoodsDto(goods);
                goodsDtoList.add(goodDto);
            }
        }
        PageInfo pageInfo = new PageInfo(goodsList);
        pageInfo.setList(goodsDtoList);
        return pageInfo;
    }

    @Override
    public PageInfo<GoodsDto> selectNewGoodsByMap(Map<String, Object> params) {
        // 分页参数
        Integer pageNum = params.containsKey("pageNum") ? Integer.parseInt(params.get("pageNum").toString()) : 1;
        Integer pageSize = params.containsKey("pageSize") ? Integer.parseInt(params.get("pageSize").toString()) : 10;

        // 服务类别ID 转换
        if (params.containsKey("categoryId")) {
            Long categoryId = Long.parseLong(params.get("categoryId").toString());
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category != null) {
                String idPath = category.getMakeSelfAsParentIds();
                params.put("idPath", idPath);
            }
        }

        PageHelper.startPage(pageNum, pageSize, "goods.create_time DESC");
        List<Goods> goodsList = goodsMapper.selectNewByMap(params);

        // 包装DTO
        List<GoodsDto> goodsDtoList = Lists.newArrayList();
        if (Collections3.isNotEmpty(goodsList)) {
            for (Goods goods : goodsList) {
                GoodsDto goodDto = fullGoodsDto(goods);
                goodsDtoList.add(goodDto);
            }
        }
        PageInfo pageInfo = new PageInfo(goodsList);
        pageInfo.setList(goodsDtoList);
        return pageInfo;
    }

    /**
     * 简介:根据商品pkgId 获取封面数组
     *
     * @param pkgId
     * @return
     * @author zhaowei
     * @Date 2016年1月6日 下午3:07:58
     * @version 1.0
     */
    private String[] getGoodsImageByPkgId(long pkgId) {
        String[] goodPics = null;
        List<ImageItem> imageitemList = imageItemService.findImageItemList(pkgId);
        if (imageitemList != null && imageitemList.size() > 0) {
            goodPics = new String[imageitemList.size()];
            for (int y = 0; y < imageitemList.size(); y++) {
                goodPics[y] = systemFileService.getFileUrlByUri(imageitemList.get(y).getUri());
            }
        } else {
            goodPics = new String[0];
        }
        return goodPics;
    }

    @Override
    public PageInfo<GoodsDto> selectGoodsByMemberId(long memberId) {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.or().andMemberIdEqualTo(memberId).andIsDelEqualTo(0);

        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        List<GoodsDto> goodDtoList = null;
        if (goodsList == null || goodsList.size() == 0) {
            goodDtoList = Collections.emptyList();
        } else {
            goodDtoList = new ArrayList<GoodsDto>();
            GoodsDto goodDto = null;
            for (Goods good : goodsList) {
                goodDto = selectGoodsDtoInfoBySn(good.getGoodsSn());
                if (goodDto != null) {
                    //查询服务标签
                    if (good.getGoodsId() != null) {
                        List<ServerTags> serverTagses = serverTagsMapper.selectServerTagsByGoodId(good.getGoodsId());
                        System.out.println("########################:"+JSON.toJSON(serverTagses));
                        if (serverTagses != null && serverTagses.size() > 0)
                            goodDto.setServerTags(serverTagses);
                    }
                    //查询服务简单描述
                    if (good.getGoodsArticleId() != null) {
                        Article article = articleMapper.selectByPrimaryKey(good.getGoodsArticleId());
                        if (article != null)
                            goodDto.setGoodBrief(article.getContent() != null ? article.getContent() : "");
                    }
                    goodDtoList.add(goodDto);
                }
            }
        }
        PageInfo pageInfo = new PageInfo(goodsList);
        pageInfo.setList(goodDtoList);
        return pageInfo;
    }

    @Override
    public PageInfo<GoodsDto> selectBestGoodsByMap(Map<String, Object> params) {
        // 分页参数
        Integer pageNum = params.containsKey("pageNum") ? Integer.parseInt(params.get("pageNum").toString()) : 1;
        Integer pageSize = params.containsKey("pageSize") ? Integer.parseInt(params.get("pageSize").toString()) : 10;

        // 服务类别ID 转换
        if (params.get("categoryId") != null) {
            Long categoryId = Long.parseLong(params.get("categoryId").toString());
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            String idPath = category.getMakeSelfAsParentIds();
            params.put("idPath", idPath);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goodsList = goodsMapper.selectBestByMap(params);

        // 包装DTO
        List<GoodsDto> goodsDtoList = Lists.newArrayList();
        if (Collections3.isNotEmpty(goodsList)) {
            for (Goods goods : goodsList) {
                GoodsDto goodDto = fullGoodsDto(goods);
                goodsDtoList.add(goodDto);
            }
        }
        PageInfo pageInfo = new PageInfo(goodsList);
        pageInfo.setList(goodsDtoList);
        return pageInfo;
    }

    private GoodsDto fullGoodsDto(Goods goods) {
        GoodsDto goodDto = new GoodsDto();
        goodDto.setGoodSn(goods.getGoodsSn());
        goodDto.setGoodId(goods.getGoodsId());
        goodDto.setCateId(goods.getCatId());
        goodDto.setType(goods.getServerType());
        goodDto.setGoodsName(goods.getGoodsName());
        goodDto.setGoodPrice(goods.getShopPrice().floatValue());
        goodDto.setGoodUnit(goods.getGoodsCompanyNote());

        // 根据会员id获取会员信息
        MemberDetail memberDetail = memberService.findMemberDetailById(goods.getMemberId());
        if (null != memberDetail) {
            // 性别
            goodDto.setGender(memberDetail.getMember().getGender());
            // 会员是否认证
            goodDto.setAuthentication(StringUtils.isEmpty(memberDetail.getMember().getRealName()) ? false : true);

            // 获取会员头像
            if (Collections3.isNotEmpty(memberDetail.getImageItemList())) {
                ImageItem imageItem = Collections3.getFirst(memberDetail.getImageItemList());
                if(null != imageItem) {
                    goodDto.setImageUrl(systemFileService.getFileUrlByUri(imageItem.getUri()));
                }
            }

            String nickName = "";
            if (StringUtils.isEmpty(memberDetail.getMember().getRealName())) {
                nickName = memberDetail.getMember().getUserName();
            } else {
                nickName = memberDetail.getMember().getRealName();
            }
            goodDto.setNickName(nickName);
            goodDto.setMemberId(goods.getMemberId());

            String address = memberDetail.getMember().getAddress();
            if (!StringUtils.isEmpty(address)) {
                List<SysArea> sysAreaList = addressService.getPathArea(Integer.parseInt(address));
                goodDto.setAddress(sysAreaList);
            }
        }


        // 根据服务id获取服务标签
        List<ServerTags> serverTags = serverTagsMapper.selectServerTagsByGoodId(goods.getGoodsId());
        goodDto.setServerTags(serverTags);

        // 根据服务图片组id获取图片集
        String[] goodPics;
        if (null != goods.getGoodsImgPkgid()) {
            goodPics = getGoodsImageByPkgId(goods.getGoodsImgPkgid());
        } else {
            goodPics = new String[0];
        }
        goodDto.setGoodPics(goodPics);

        // 根据商品id获取关注数
        int count = goodFollowService.countGoodFollowByGoodId(goods.getGoodsId());
        goodDto.setFollowCount(count);

        // 获取服务内容
        if (goods.getGoodsArticleId() != null) {
            Article article = articleService.selectById(goods.getGoodsArticleId());
            if (article != null) {
                goodDto.setContent(article.getContent());
            }
        }


        return goodDto;
    }

    @Override
    public PageInfo<Goods> selectByGoodsId(long id) {
        List<Goods> goods = goodsMapper.selectByGoodsId(id);
        return new PageInfo(goods);
    }

    @Override
    public GoodsDto selectGoodsDtoBySn(String goodsSn) {
        Goods goods = selectGoodsByGoodsId(goodsSn);
        GoodsDto goodsDto = null;
        if (goods != null) {
            goodsDto = new GoodsDto();
            goodsDto.setGoodId(goods.getGoodsId());
            goodsDto.setGoodSn(goods.getGoodsSn());
            goodsDto.setCateId(goods.getCatId());
            goodsDto.setGoodsName(goods.getGoodsName());
            goodsDto.setGoodPrice(goods.getShopPrice().floatValue());
            goodsDto.setGoodUnit(goods.getGoodsCompanyNote());
            goodsDto.setType(goods.getServerType());
            goodsDto.setPkgId(goods.getGoodsImgPkgid());
            goodsDto.setGoodId(goods.getGoodsId());
            // 根据商品id获取关注数
            int count = goodFollowService.countGoodFollowByGoodId(goods.getGoodsId());
            goodsDto.setFollowCount(count);

            // 根据服务id获取服务标签
            List<ServerTags> serverTags = serverTagsMapper.selectServerTagsByGoodId(goods.getGoodsId());
            goodsDto.setServerTags(serverTags);

            // 获取封面图片
            Long pkgId = goods.getGoodsImgPkgid();
            if (pkgId != null && pkgId.longValue() != 0) {
                String[] goodPics = getGoodsImageByPkgId(goods.getGoodsImgPkgid());
                goodsDto.setGoodPics(goodPics);
                if (goodPics != null && goodPics.length > 0) {
                    goodsDto.setGoodPic(goodPics[0]);
                }
            }


            // 商家会员id
            goodsDto.setMemberId(goods.getMemberId());

            // 根据会员id获取会员信息
            MemberDetail memberDetail = memberService.findMemberDetailById(goods.getMemberId());
            if (null != memberDetail) {
                String imageUrl = "";
                // 获取会员头像
                if (null != memberDetail.getImageItemList() && memberDetail.getImageItemList().size() > 0) {
                    ImageItem imageItem = memberDetail.getImageItemList().get(0);
                    imageUrl = imageItem.getUri();
                }
                goodsDto.setImageUrl(imageUrl);
                // 商家会员名称
                String nickName = "";
                if (StringUtils.isEmpty(memberDetail.getMember().getRealName())) {
                    nickName = memberDetail.getMember().getUserName();
                } else {
                    nickName = memberDetail.getMember().getRealName();
                }
                goodsDto.setNickName(nickName);
            }
        }
        return goodsDto;
    }

    @Override
    public GoodsDto selectGoodsDtoInfoBySn(String goodsSn) {
        GoodsDto goodsDto = selectGoodsDtoBySn(goodsSn);
        if (goodsDto != null) {
            //售出数
            int sallCount = selectSallGoodsCount(goodsDto.getGoodSn());
            goodsDto.setSallCount(sallCount);
            // 收藏数
            int collectionCount = collectionService.selectCountByGoodsId(goodsDto.getGoodId());
            goodsDto.setCollectionCount(collectionCount);
            // 评价数
            int commentCount = goodsCommentService.selectCountByGoodsId(goodsDto.getGoodId());
            goodsDto.setEvaluateCount(commentCount);
            // 获取封面图片
            Long pkgId = goodsDto.getPkgId();
            if (pkgId != null && pkgId.longValue() != 0) {
                String[] goodPics = getGoodsImageByPkgId(pkgId);
                if (goodPics != null && goodPics.length > 0) {
                    goodsDto.setGoodPics(goodPics);
                }
            }
        }
        return goodsDto;
    }

    @Override
    public int selectSallGoodsCount(String goodsSn) {
        return goodsMapper.selectSallGoodsCount(goodsSn);
    }

    @Override
    public int countPublishGoods() {
        Integer i = goodsMapper.countPublishGoods();
        return i == null ? 12321 : i;
    }

    @Override
    public List<GoodsDto> selectGoodsDtoByOrderId(long orderId) {
        List<GoodsDto> goodsDtoList = null;
        List<OrderGoods> orderGoodsList = orderGoodsService.selectOrderGoodsByOrderId(orderId);
        if (orderGoodsList != null && orderGoodsList.size() > 0) {
            goodsDtoList = new ArrayList<GoodsDto>();
            for (OrderGoods og : orderGoodsList) {
                GoodsDto goodsDto = selectGoodsDtoBySn(og.getGoodsSn());
                if (goodsDto != null) {
                    goodsDtoList.add(goodsDto);
                }
            }
        }
        return goodsDtoList;
    }

    @Override
    public Integer countGoodsPage() {
        return goodsMapper.countGoodsPage();
    }

    @Override
    public List<Goods> selectByGoods(Integer pageNum, Integer pageSize, Goods params) {
        GoodsExample sql = new GoodsExample();
        GoodsExample.Criteria criteria = sql.or();
        if (null != params.getGoodsId()) {
            criteria.andGoodsIdEqualTo(params.getGoodsId());
        }
        if (null != params.getIsDel()) {
            criteria.andIsDelEqualTo(params.getIsDel());
        }
        if (null != params.getMemberId()) {
            criteria.andMemberIdEqualTo(params.getMemberId());
        }
        if (null != params.getGoodsStatus()) {
            criteria.andGoodsStatusEqualTo(params.getGoodsStatus());
        }
        if (null != params.getIsSale()) {
            criteria.andIsSaleEqualTo(params.getIsSale());
        }
        PageHelper.startPage(pageNum, pageSize, "goods.update_time desc");
        List<Goods> goodsList = goodsMapper.selectByExample(sql);
        return goodsList;
    }

    @Override
    public boolean update(Long goodsId, Long memberId, Goods setValue) {
        GoodsExample sql = new GoodsExample();
        sql.or().andMemberIdEqualTo(memberId).andGoodsIdEqualTo(goodsId);
        return goodsMapper.updateByExampleSelective(setValue, sql) > 0;
    }

    @Override
    public boolean isExist(Long goodsId, Long memberId) {
        GoodsExample sql = new GoodsExample();
        sql.or().andGoodsIdEqualTo(goodsId).andMemberIdEqualTo(memberId);
        int count = goodsMapper.countByExample(sql);
        return count > 0;
    }

    @Override
    public Goods findByIdAndMemberId(Long goodsId, Long memberId) {
        GoodsExample sql = new GoodsExample();
        sql.or().andGoodsIdEqualTo(goodsId).andMemberIdEqualTo(memberId);
        List<Goods> goodsList = goodsMapper.selectByExample(sql);
        return Collections3.getFirst(goodsList);
    }
}
